<template>
  <a-form layout="vertical" @finish="handleSubmit" :model="form" class="register-form">

    <!-- 用户名 -->
    <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名!' }]">
      <a-input v-model:value="form.username">
        <template #prefix>
          <UserOutlined />
        </template>
      </a-input>
    </a-form-item>

    <!-- 账户 -->
    <a-form-item label="账户" name="account" :rules="[{ required: true, message: '请输入账户!' }]">
      <a-input v-model:value="form.account">
        <template #prefix>
          <IdcardOutlined />
        </template>
      </a-input>
    </a-form-item>

    <!-- 密码 -->
    <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
      <a-input-password v-model:value="form.password">
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>

    <!-- 性格 -->
    <a-form-item label="性格描述" name="personality" :rules="[{ required: true, message: '请简单描述您的性格!' }]">
      <a-textarea v-model:value="form.personality" :rows="3" placeholder="例：外向开朗，喜欢技术交流" />
    </a-form-item>

    <!-- 注册按钮 -->
    <a-form-item>
      <a-button type="primary" html-type="submit" block class="register-btn">
        立即注册
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import {
  UserOutlined,
  LockOutlined,
  IdcardOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import axios from '../utils/axios';

const router = useRouter();
const form = ref({
  username: '',
  account: '',
  password: '',
  personality: '',
});

//处理注册提交请求的函数
const handleSubmit = async () => {
  const formData = new FormData();
  formData.append('username', form.value.username);
  formData.append('account', form.value.account);
  formData.append('password', form.value.password);
  formData.append('personality', form.value.personality);

  try {
    const response = await axios.post('/users/register', {
      username: form.value.username,
      account: form.value.account,
      password: form.value.password,
      personality: form.value.personality
    });
    message.success(response.data.message);
    console.log('注册成功:', formData);
    router.push('/auth');
  } catch (error) {
    if (error.response?.status === 400) {
      message.error("账户及用户名已经存在！")
    }
    if (error.response?.data?.error) {
      console.error('服务器返回详细错误:', error.response.data.error);
    }
  }
};
</script>

<style scoped>

.register-form {
  max-width: 500px;
  margin: 0 auto;
  padding: 24px;
}

.register-btn {
  margin-top: 20px;
  height: 40px;
}
</style>